﻿using Consul;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsulTestClient.Helper
{
    public class ConsulService
    {
        /// <summary>
        /// 获取请求路径
        /// </summary>
        /// <param name="consulUri">consul地址</param>
        /// <param name="centerName">数据中心名称</param>
        /// <param name="reqUri">请求地址,会根据 分组名称自动解析成相应的ip地址</param>
        /// <returns></returns>
        public static string Convert(string consulUri, string centerName, string reqUri)
        {
            ConsulClient client = new ConsulClient(x =>
            {
                x.Address = new Uri(consulUri);
                x.Datacenter = centerName;
            });

            //获取consul中注册的服务列表
            var consulServiceList = client.Agent.Services().Result.Response;

            //统一请求地址
            Uri uri = new Uri(reqUri);

            //取出分组名称
            string groupName = uri.Host;

            //匹配出对应的服务
            var serviceList = consulServiceList.Where(x => x.Value.Service.ToLower().Equals(groupName.ToLower())).ToArray();

            //随机访问策略
            var service = serviceList[new Random().Next(serviceList.Length)].Value;

            return $"{uri.Scheme}://{service.Address}:{service.Port}{uri.PathAndQuery}";
        }
    }
}
